/**
 * 权限声明：
 */
package com.handy.webwork.view;

import java.io.IOException;
import java.util.Locale;

import javax.servlet.ServletContext;

import com.handy.webwork.config.HandyConfiguration;

import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.cache.WebappTemplateLoader;
import freemarker.template.Template;

/**
 * freemarker模板工厂。
 * 
 * @author rocken.zeng@gmail.com
 * 
 */
public class FreemarkerTemplateFactory {
	private static FreemarkerTemplateFactory instance = null;
	private freemarker.template.Configuration cfg = new freemarker.template.Configuration();

	public static synchronized FreemarkerTemplateFactory getInstance() {
		if (instance == null) {
			instance = new FreemarkerTemplateFactory();
		}
		return instance;
	}

	public void init(ServletContext context) {
		//cfg.setServletContextForTemplateLoading(context, "");//站点所在路径中查找模板
		//cfg.setClassForTemplateLoading(this.getClass(), "/"); //在classes中查找模板   

		ClassTemplateLoader ct = new ClassTemplateLoader(getClass(), "/");
		WebappTemplateLoader wt = new WebappTemplateLoader(context,"");
		
		TemplateLoader[] loaders = new TemplateLoader[] { ct,wt };
		MultiTemplateLoader mtl = new MultiTemplateLoader(loaders);//在多个位置查找模板
		cfg.setTemplateLoader(mtl);
		
		if (null != HandyConfiguration
				.freemarkers(HandyConfiguration.FREEMARKER_NUMBER_FORMAT)) {
			cfg.setNumberFormat((String) HandyConfiguration
					.freemarkers(HandyConfiguration.FREEMARKER_NUMBER_FORMAT));
		}

		if (null != HandyConfiguration
				.freemarkers(HandyConfiguration.FREEMARKER_LOCALE)) {
			cfg.setLocale(new Locale((String) HandyConfiguration
					.freemarkers(HandyConfiguration.FREEMARKER_LOCALE)));
		}

		if (null != HandyConfiguration
				.freemarkers(HandyConfiguration.FREEMARKER_DATE_FORMAT)) {
			cfg.setDateFormat((String) HandyConfiguration
					.freemarkers(HandyConfiguration.FREEMARKER_DATE_FORMAT));
		}

		if (null != HandyConfiguration
				.freemarkers(HandyConfiguration.FREEMARKER_DATETIME_FORMAT)) {
			cfg
					.setDateTimeFormat((String) HandyConfiguration
							.freemarkers(HandyConfiguration.FREEMARKER_DATETIME_FORMAT));
		}

		if (null != HandyConfiguration
				.properties(HandyConfiguration.PROP_ENCODING)) {
			cfg.setDefaultEncoding((String) HandyConfiguration
					.properties(HandyConfiguration.PROP_ENCODING));
		} else {
			cfg.setDefaultEncoding("utf-8");
		}

		if (null != HandyConfiguration
				.freemarkers(HandyConfiguration.FREEMARKER_CACHE)) {
			String _cache = HandyConfiguration
					.freemarkers(HandyConfiguration.FREEMARKER_CACHE);
			if (_cache.equals("true")) {
				cfg.setCacheStorage(new freemarker.cache.MruCacheStorage(20,
						250));
			}
		}
	}

	public Template create(String fileName) throws IOException {
		return cfg.getTemplate(fileName);
	}
}
